package com.eras.shoes.ui

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.eras.shoes.MainActivity
import com.eras.shoes.contents.Api
import com.eras.shoes.contents.Global
import com.eras.shoes.contents.UserBean
import com.eras.shoes.databinding.ActivityLoginBinding
import com.eras.shoes.utils.OkHttpUtils
import com.eras.shoes.utils.OkHttpUtils.DataCallBack
import com.eras.shoes.utils.ToastUtils
import com.google.gson.Gson
import okhttp3.Request
import org.json.JSONObject
import java.io.IOException


class LoginActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLoginBinding
    private val sharedPref by lazy {
        getSharedPreferences("login_prefs", Context.MODE_PRIVATE)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 检查并请求存储权限
        checkAndRequestStoragePermission()
        checkAutoLogin()
//
//        binding.btnLogin.setOnClickListener {
//            // 方式1：直接抛出异常（最简单）
//            throw RuntimeException("手动触发的测试崩溃！")
//        }

        binding.btnLogin.setOnClickListener {
            val username = binding.etUsername.text.toString()
            val password = binding.etPassword.text.toString()

            if (validateInput(username, password)) {
                performLogin(username, password, binding.cbRemember.isChecked)
            }
        }
    }

    private fun checkAutoLogin() {
        if (sharedPref.getBoolean("is_auto_login", false)) {
            val savedUsername = sharedPref.getString("username", "")
            val savedPassword = sharedPref.getString("password", "")

            if (!savedUsername.isNullOrEmpty() && !savedPassword.isNullOrEmpty()) {
                binding.etUsername.setText(savedUsername)
                binding.etPassword.setText(savedPassword)
                binding.cbRemember.isChecked = true
                performLogin(savedUsername, savedPassword, true)
            }
        }
    }

    private fun performLogin(username: String, password: String, remember: Boolean) {
        binding.progressBar.visibility = View.VISIBLE
        signIn(username, password, remember)

        // 模拟网络请求
//        Handler(Looper.getMainLooper()).postDelayed({
//
//            if (username == "admin" && password == "123456") {
//                saveLoginState(username, password, remember)
//                startActivity(Intent(this, MainBoardActivity::class.java))
//                finish()
//            } else {
//                Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show()
//            }
//        }, 1500)
    }

    private fun saveLoginState(
        username: String,
        password: String,
        remember: Boolean,
        token: String
    ) {
        with(sharedPref.edit()) {
            putBoolean("is_auto_login", remember)
            if (remember) {
                putString("username", username)
                putString("password", password)
                putString("token", token)
            } else {
                remove("username")
                remove("password")
                remove("token")
            }
            apply()
        }
    }

    private fun validateInput(username: String, password: String): Boolean {
        if (username.isEmpty()) {
            binding.etUsername.error = "请输入用户名"
            return false
        }
        if (password.isEmpty()) {
            binding.etPassword.error = "请输入密码"
            return false
        }
        return true
    }

    private fun signIn(username: String, password: String, remember: Boolean) {
        val user = UserBean("", "")
        user.account = username
        user.password = password
        val data = Gson().toJson(user)
        OkHttpUtils.postJsonNoAuthAsync(Api.signIn, data, object : DataCallBack {
            override fun requestFailure(request: Request, e: IOException) {
                Log.e("LoginActivity", "登录失败")
            }

            @Throws(Exception::class)
            override fun requestSuccess(result: String) {
                binding.progressBar.visibility = View.GONE
                val toJsonObj = JSONObject(result)
                Log.e("LoginActivity", "登录返回" + toJsonObj)
                val code = toJsonObj.getInt("code")
                if (code == 0) {
                    val jsonData = toJsonObj.getJSONObject("data")
                    val token = jsonData.getString("token")
                    Global.token = token
                    val message = toJsonObj["message"] as String
                    ToastUtils().show(this@LoginActivity, "登录" + message)
                    saveLoginState(username, password, remember, token)
                    startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                    finish()
                } else {
                    val message = toJsonObj["message"] as String
                    ToastUtils().show(this@LoginActivity, message)
                }
            }
        })
    }

    // 需要请求的权限列表（根据功能需求调整）
    private val requiredPermissions = mutableListOf<String>().apply {
        // 基础权限（Android 6.0+）
        add(Manifest.permission.CAMERA)
        add(Manifest.permission.READ_CONTACTS)

        // Android 10 (API 29) 分区存储
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            add(Manifest.permission.ACCESS_MEDIA_LOCATION)
        }

        // Android 13 (API 33) 新增的媒体权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            add(Manifest.permission.READ_MEDIA_IMAGES)
            add(Manifest.permission.READ_MEDIA_VIDEO)
            add(Manifest.permission.READ_MEDIA_AUDIO)
        } else {
            // 旧版本使用传统存储权限
            add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
    }.toTypedArray()

    private fun checkAndRequestStoragePermission() {
        val ungrantedPermissions = requiredPermissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }

        if (ungrantedPermissions.isNotEmpty()) {
            // 请求未授予的权限
            ActivityCompat.requestPermissions(
                this,
                ungrantedPermissions.toTypedArray(),
                PERMISSION_REQUEST_CODE
            )
        } else {
            // 所有权限已授予
            onAllPermissionsGranted()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_REQUEST_CODE) {
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }

            if (allGranted) {
                onAllPermissionsGranted()
            } else {
                // 处理拒绝的权限
                permissions.forEachIndexed { index, permission ->
                    if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
                        // 检查用户是否选择"不再询问"
                        val shouldShowRationale = ActivityCompat.shouldShowRequestPermissionRationale(
                            this, permission
                        )

                        if (!shouldShowRationale) {
                            // 用户勾选"不再询问"，需要引导用户去设置页
                            showPermissionSettingsDialog()
                            return
                        }
                    }
                }
                // 部分权限被拒绝但未选"不再询问"
                showPermissionRationale()
            }
        }
    }

    private fun onAllPermissionsGranted() {
        // 所有权限获取成功，执行业务逻辑
        Toast.makeText(this, "存储管理权限已授予", Toast.LENGTH_SHORT).show()
    }

    private fun showPermissionRationale() {
        // 显示解释为什么需要这些权限的对话框
        Toast.makeText(this, "存储管理权限被拒绝", Toast.LENGTH_SHORT).show()
    }

    private fun showPermissionSettingsDialog() {
        // 引导用户前往应用设置页面手动开启权限
        Toast.makeText(this, "无法打开设置，请手动设置权限", Toast.LENGTH_SHORT).show()
    }

    companion object {
        private const val PERMISSION_REQUEST_CODE = 1001
    }
}
